package 题目集.hash.基数排序;

import org.junit.Test;

/**
 * 归并思想 {@link 题目集.hash.基数排序.demo02_合并K个升序链表}
 * https://leetcode.cn/problems/merge-k-sorted-lists/description/
 */
public class demo02_合并K个升序链表 {
    static int maxv = (int) 1e4;
    static int maxn = ((int) 1e4 << 1) + 10;


    public ListNode mergeKLists(ListNode[] lists) {
        ListNode[] headMap = new ListNode[maxn];
        ListNode[] tailMap = new ListNode[maxn];
        for (ListNode curr : lists) {
            while (curr != null) {
                int offset = curr.val + maxv;
                ListNode tail = tailMap[offset];
                if (tail == null) {
                    headMap[offset] = curr;
                    tailMap[offset] = curr;
                } else {
                    tail.next = curr;
                    tailMap[offset] = curr;
                }
                curr = curr.next;
            }
        }
        ListNode res = new ListNode();
        ListNode preTail = res;
        for (int i = 0; i < tailMap.length; i++) {
            if (headMap[i] != null) {
                preTail.next = headMap[i];
                preTail = tailMap[i];
            }
        }
        return res.next;
    }

    @Test
    public void test() {
        ListNode[] arr = new ListNode[3];
        arr[0] = new ListNode(1);
        arr[0].next = new ListNode(4);
        arr[0].next.next = new ListNode(5);

        arr[1] = new ListNode(1);
        arr[1].next = new ListNode(3);
        arr[1].next.next = new ListNode(4);

        arr[2] = new ListNode(2);
        arr[2].next = new ListNode(6);

        ListNode listNode = mergeKLists(arr);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
